package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.hosp.repository.DepartmentRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    /**
     * 添加科室信息
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        //1 把paramMap变成对象,使用fastjson
        //1.1 把map变成json字符串
        String jsonString = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);

        //判断是否已存在,存在则更新,不存在则添加
        //查询科室是否存在  医院编号 + 科室编号
        Department existDepartment = departmentRepository.findByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());

        if (existDepartment != null) {
            department.setId(department.getId());
            department.setCreateTime(existDepartment.getCreateTime());
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        } else {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        }

        departmentRepository.save(department);
    }

    /**
     * 分页查询
     *
     * @param page    当前页码
     * @param limit   每页记录数
     * @param hoscode 查询条件
     * @return
     */

    @Override
    public Page<Department> selectPage(int page, int limit, String hoscode) {
        //根据条件查询
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);

        //设置排序规则(可选)
        Sort sort = Sort.by(Sort.Direction.DESC, "creatTime");

        //设置分页参数
        PageRequest pageable = PageRequest.of(page - 1, limit, sort);

        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    /**
     * 删除科室信息
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void remove(String hoscode, String depcode) {
        //根据医院编号 + 科室编号查询
        Department department = departmentRepository.findByHoscodeAndDepcode(hoscode, depcode);
        //根据查询获取的ID 删除对应的科室信息
        if (department != null) {
            departmentRepository.deleteById(department.getId());
        }
    }

    /**
     * 查询科室列表(大科室->子科室)
     *
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //创建集合接收科室诗句
        List<DepartmentVo> departmentVoList = new ArrayList<>();
        //创建查询条件,根据医院编号查询所有的科室信息
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);
        List<Department> departmentList = departmentRepository.findAll(example);

        /**
         * 根据大科室编号做分组查询,得到map集合
         * @param departmentMap 大科室编号 + 名称
         *                      key:value ==> 大科室编号:对应的小科室列表
         * departmentList.stream().collect(Collectors.groupingBy(item -> item.getBigcode))
         *                      Department::getBigcode ==> 对象名:实例方法名
         */
        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        //遍历Map集合(departmentMap.entrySet()) 组装List<DepartmentVo>
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            String bigCode = entry.getKey(); //大部门编号
            List<Department> subLis = entry.getValue(); //子记录列表

            //组装List<DepartmentVo>
            //封装大科室对象DepartmentVo
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(bigCode);
            //小科室任意一条数据都有对应的bigname属性
            departmentVo.setDepname(subLis.get(0).getBigname());

            //封装小科室列表
            ArrayList<DepartmentVo> subVoList = new ArrayList<>();
            for (Department subLi : subLis) {
                DepartmentVo subDepertmentVo = new DepartmentVo();
                subDepertmentVo.setDepcode(subLi.getDepcode());
                subDepertmentVo.setDepname(subLi.getDepname());

                subVoList.add(subDepertmentVo);
                //departmentVo.getChildren().add(subDepertmentVo);
            }
            //把小科室list集合放到大科室的children里面
            departmentVo.setChildren(subVoList);
            //放到最终departmentVoList里面
            departmentVoList.add(departmentVo);
        }

        //返回List<DepartmentVo>集合
        return departmentVoList;
    }
}
